public class OpportunitySolutionExtensionController{
    public List<SolutionComponent__c> components{get;set;}
    public List<string> componentFields{get;set;}
    public Solution__c soln {get; set;}
    public String compIdx{get;set;}
    
    public Boolean IsTechnology{get;set;}
    public Boolean IsConsulting{get;set;}
    public Boolean IsOutsourcing{get;set;}
    
    private List<string> solFieldsToActivate;
 
	public Boolean IsAccountSolution{get; set;}
    
    public Boolean disableInput{get; set;}
    public string toDelete{ get; set; }
    
    public String SolutionComponentsTitle{get; set;}
    
    public String RecType{get;set;}
    private ApexPages.StandardController solnController;
              
    public OpportunitySolutionExtensionController(ApexPages.StandardController stdController) {
                setAllSolFieldsActive();
        stdController.addFields(solFieldsToActivate);
        solnController = stdController;
        soln = (Solution__c)stdController.getRecord();       
            
    }
        
        private void setAllSolFieldsActive(){
        
        solFieldsToActivate = new List<string>();         
        Schema.DescribeSObjectResult solobj = Solution__c.SObjectType.getDescribe(); 
        Map<String, Schema.SObjectField> allFieldsMap = solobj.fields.getMap();

        for(String fldName : allFieldsMap.keySet()){
            Schema.SObjectField fld = allFieldsMap.get(fldName);
            DescribeFieldResult fieldResult = fld.getDescribe();
            if(fieldResult.isCustom()){
                
                    string fieldName = fieldResult.getName();
                        solFieldsToActivate.add(fieldName);
            }
        }        
    }  
    public void Initialise(){        
        components = new List<SolutionComponent__c>();
        Schema.DescribeSObjectResult R = Solution__c.SObjectType.getDescribe();
        
        Schema.DescribeSObjectResult solcomp = SolutionComponent__c.SObjectType.getDescribe(); 
        Map<String, Schema.SObjectField> allFieldsMap = solcomp.fields.getMap();
        String SOQLSelect = '';
        for(String fldName : allFieldsMap.keySet()){
            Schema.SObjectField fld = allFieldsMap.get(fldName);
            DescribeFieldResult fieldResult = fld.getDescribe();
            string fieldName = fieldResult.getName();
            System.debug('Got field:'+fieldName);
            if(SOQLSelect != ''){
                SOQLSelect += ',' + fieldName;
            }
            else{
                SOQLSelect += 'select ' + fieldName;
            }     
        }             
        if(soln.id !=null){
            String SOQLStmt =SOQLSelect + ' from SolutionComponent__c where Solution__r.id =' + '\'' + soln.id + '\'';        
            components = Database.query(SOQLStmt);
        }              
        Map<ID,Schema.RecordTypeInfo> recTypesMap = R.getRecordTypeInfosByID();
        Schema.RecordTypeInfo recTypeInst = recTypesMap.get(soln.RecordTypeId);         
        RecType = recTypeInst.getName();       
        IsTechnology = (RecType == 'HR Technology');
        IsConsulting = (RecType == 'HR Consulting');
        IsOutsourcing = (RecType == 'HR Outsourcing');
        
        if(soln.Account__c != null)
        {
                IsAccountSolution = true;
        }
        else
        {
                IsAccountSolution = false;
        }        
        techodisable();       
    }
    
    Public void currencyDefault()
    {
        system.debug('solution id ' + soln.id);
        if(soln.id != null){
        Solution__c sln = [select CurrencyIsoCode,Opportunity__r.id from Solution__c where id =: soln.id]; 
        opportunity opty = [select CurrencyIsoCode from opportunity where id =: sln.Opportunity__r.id];
        sln.currencyIsoCode = opty.CurrencyIsoCode;        
                          
        system.debug('solution id ++++  ' + soln.id);
       
        }    
    }
    
    public void NewSolutionComponent(){
       
        SolutionComponent__c solComp = new SolutionComponent__c();
        solComp.ParentType__c = soln.product__c;
        solComp.Solution__c = null;
        components.add(solComp);
        techodisable();
        
    }
        
 public PageReference save() {
        Savepoint sp = Database.setSavepoint();
        PageReference retPage = null;
        try {       	
        	if(IsAccountSolution)
        	{
        		if(soln.Opportunity__c == null){
        			DummyOptyHolder__c optyCustomSetting = DummyOptyHolder__c.getInstance();
            		string DumyOptyId = optyCustomSetting.OptyId__c;
					soln.Opportunity__c=DumyOptyId;
        		}
				soln.IsAccountSolution__c = true;            	
            	system.debug('Account Saving Solution');
				solnController.save();
        		soln = (Solution__c)solnController.getRecord();
            	Solution__c sol=[select id,Opportunity__c,Account__c from Solution__c where id=:soln.Id];
            	retPage = new PageReference('/'+sol.Account__c);
            	system.debug('Set Account Save Page Solution'); 
        		
        	}
        	else
        	{
        		system.debug('Not Account Saving Solution');
				solnController.save();
        		soln = (Solution__c)solnController.getRecord();
        		Solution__c sol=[select id,Opportunity__c,Account__c from Solution__c where id=:soln.Id];
        		retPage=new PageReference('/'+sol.Opportunity__c);
        		system.debug('Set Opty Save Page Solution');        		
        	}
        	
            
            
			for (SolutionComponent__c solComp : components){
				if(solComp.Solution__c == null)
                {
                	solComp.Solution__c = soln.Id;                   
               	}
                currencyDefault();  
                solComp.CurrencyIsoCode = soln.CurrencyIsoCode;
                system.debug('solution component currencycode' + solComp.CurrencyIsoCode);
                	
            }
            if(components.size() > 0)
            {
            	Database.upsert(components);
            }
           
            return retPage;                              
                                         
        }
        catch (Exception e) {
            Database.rollback(sp);
            System.debug('******** exception ' + e);
        }
        return null;
        
    }
    
    public PageReference cancel(){
      
        PageReference p;
        p =  solnController.cancel();
        try{
            soln = (Solution__c)solnController.getRecord(); 
            Solution__c sol=[select id,Opportunity__c,Account__c from Solution__c where id=:soln.Id];
            DummyOptyHolder__c optyCustomSetting = DummyOptyHolder__c.getInstance();
            string DumyOptyId = optyCustomSetting.OptyId__c;
			
			if(IsAccountSolution)
        	{
        		p=new PageReference('/'+sol.Account__c);
        	}
        	else
        	{
        		 p=new PageReference('/'+sol.Opportunity__c);	
        	}
        }
        catch(Exception e){
            System.debug('******* exception' + e);        
        }
        return p;
    }
    
   public void deleteSectionItem() {
        SolutionComponent__c solComp;
        System.debug('Component Index Reference' + compIdx);
        String[] columnparts = compIdx.split(':');
        
        Integer idx =0;
        Integer tableRow;
        
        for(String tkn : columnparts){ 
                
                if(tkn == 'DeleteColumn'){
                        tableRow = Integer.valueOf(columnparts[idx-1]);
                        System.debug('Table Row Is: ' +tableRow );
                }
                idx++;          
        }
        
        System.Debug('todelete'+todelete);
        if(this.toDelete != '' || this.toDelete != null){
            try{                            
                                                        List<SolutionComponent__c> modcomponents = new List<SolutionComponent__c>();
                idx =0;
                for(SolutionComponent__c comp: components){
                                        if(idx != tableRow){
                                                 modcomponents.add(comp);
                                        }
                                        idx++;
                }
                components = modcomponents;
                solComp = [select id from SolutionComponent__c where id = : this.toDelete];                   
                delete solComp;
                
                              
            }
            catch(Exception e){
                System.Debug('Error while deletion:'+e);
            }
            techodisable();
                        

        }        
    }
    
    public void oppchange()
    {
     soln = (Solution__c)solnController.getRecord();
     
     if(soln.Opportunity__c==null)
     {
      
      DummyOptyHolder__c optyCustomSetting = DummyOptyHolder__c.getInstance();
      string DumyOptyId = optyCustomSetting.OptyId__c;
      soln.Opportunity__c=DumyOptyId ;
       
     }
    }
    
    public void techodisable(){
        if(components.size() > 0){
            disableInput = true;
        }
        else{
            disableInput = false;
        }
    }
}